package com.socket.server.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.socket.server.model.po.ChatRecord;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ChatRecordMapper extends BaseMapper<ChatRecord> {
    @Select("SELECT c.* FROM chat_record AS c\n" +
            "JOIN (\n" +
            " SELECT LEAST(guid, target) AS sender," +
            " GREATEST(guid, target) AS receiver," +
            " MAX(id) AS latestId\n" +
            "  FROM chat_record\n" +
            "  WHERE guid = #{guid} OR target = #{guid} and reject = 0 and deleted = 0\n" +
            "  GROUP BY LEAST(guid, target), GREATEST(guid, target)\n" +
            ") AS t\n" +
            "ON c.guid = t.sender AND c.target = t.receiver AND c.id = t.latestId\n" +
            "ORDER BY c.create_time DESC;")
    List<ChatRecord> selectPreviewByUser(String guid);

    @Select("SELECT c1.*\n" +
            "FROM chat_record c1\n" +
            "JOIN (\n" +
            "  SELECT target, MAX(id) AS max_id\n" +
            "  FROM chat_record\n" +
            "  WHERE (target LIKE '#%' OR target = #{defGroupId})\n" +
            "  AND reject = 0\n" +
            "  AND deleted = 0\n" +
            "  GROUP BY target\n" +
            ") c2 ON c1.id = c2.max_id\n" +
            "WHERE c1.target IN (\n" +
            "  SELECT g.guid AS target\n" +
            "  FROM sys_group g, sys_group_user gu\n" +
            "  WHERE g.guid = gu.gid\n" +
            "  AND gu.uid = #{guid}\n" +
            "  AND g.deleted = 0\n" +
            "  AND gu.deleted = 0\n" +
            ")")
    List<ChatRecord> selectPreviewByGroup(String guid, String defGroupId);
}
